<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    :minHeight="100"
  >
    <div class="p-4">
      <BasicForm @register="registerForm">
        <template #value="{ model, field }">
          <FormItemRest>
            <Select
              :options="dataRef['options']"
              v-model:value="model[field]"
              :fieldNames="{ label: 'name' }"
              v-if="model['type'] === 'select'"
            />
            <Select
              :options="isOrNooptions"
              v-model:value="model[field]"
              v-else-if="model['type'] === 'boolean'"
            />
            <InputTextArea v-model:value="model[field]" v-else-if="model['type'] === 'textarea'" />
            <Input v-model:value="model[field]" v-else />
          </FormItemRest>
        </template>
      </BasicForm>
      <template v-if="dataRef['type'] === 'select'">
        <div class="text-right">
          <a-button type="primary" size="small" @click="hanldeOptionsCreate">新增</a-button>
        </div>
        <Table :dataSource="dataRef['options']" :columns="optionsColumns" :pagination="false" />
      </template>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, unref, reactive, computed, h } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { FormSchema } from '/@/components/Table';
  import { BasicForm, useForm } from '/@/components/Form/index';
  // import { useModal } from '/@/components/Modal';
  import { Input, Select, Form, Table } from 'ant-design-vue';
  import { DeleteOutlined } from '@ant-design/icons-vue';
  import { getConfigCreateConfigItem } from '/@/api/flowManage/flowManage';
  import { isArray } from '/@/utils/is';
  import { useMessage } from '/@/hooks/web/useMessage';
  export default defineComponent({
    components: {
      BasicModal,
      BasicForm,
      Input,
      Select,
      InputTextArea: Input.TextArea,
      FormItemRest: Form.ItemRest,
      Table,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();
      let isUpdate = ref(true);
      let dataRef = ref<Recordable>({ options: [], kind: '' });

      const [registerModal, { setModalProps, closeModal, updateSchema }] = useModalInner(
        async (data) => {
          resetFields();
          setModalProps({ confirmLoading: false, width: '50%' });
          isUpdate.value = !!data?.isUpdate;
          setFieldsValue({ ...unref(dataRef) });
        },
      );
      const isOrNooptions = ref([
        {
          label: '是',
          value: 'true',
        },
        {
          label: '否',
          value: 'false',
        },
      ]);
      const FormSchema: FormSchema[] = [
        {
          field: 'kind',
          label: '分类',
          component: 'Select',
          defaultValue: '',
          componentProps: {
            options: [
              { label: '全部', value: '' },
              { label: '流程', value: 'flow' },
              { label: '文档', value: 'fileark' },
              { label: '界面', value: 'ui' },
              { label: '人事', value: 'hr' },
              { label: '计划', value: 'workplan' },
              { label: '手机端', value: 'mobile' },
              { label: '系统', value: 'system' },
              { label: '智能模块', value: 'module' },
              { label: '其它', value: 'other' },
            ],
            allowClear: false,
            getPopupContainer: () => document.body,
          },
          colProps: { lg: 24, md: 24 },
        },
        {
          field: 'name',
          label: '配置项',
          component: 'Input',
          required: true,
          colProps: {
            span: 24,
          },
          componentProps: {
            placeholder: '请填写英文或英文数字组合',
          },
        },
        {
          field: 'desc',
          label: '标题',
          component: 'Input',
          required: true,
          colProps: {
            span: 24,
          },
        },
        {
          field: 'type',
          label: '类型',
          component: 'Select',
          required: true,
          defaultValue: 'input',
          componentProps: {
            options: [
              { label: '选择型', value: 'select' },
              { label: '布尔型', value: 'boolean' },
              { label: '多行文本', value: 'textarea' },
              { label: '单行文本', value: 'input' },
            ],
            allowClear: false,
            getPopupContainer: () => document.body,
            onChange: (value) => {
              dataRef.value.type = value;
              setFieldsValue({ value: undefined });
            },
          },
          colProps: { lg: 24, md: 24 },
        },
        {
          field: 'value',
          label: '值',
          component: 'Input',
          required: true,
          colProps: {
            span: 24,
          },
          slot: 'value',
        },
      ];
      const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
        labelWidth: 100,
        schemas: FormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });

      const getTitle = '新增';

      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          const formData = Object.assign({}, dataRef.value, values);
          if (formData.type != 'select') {
            formData.options = [];
          }
          formData.options = JSON.stringify(formData.options);
          console.log('formData', formData);
          await getConfigCreateConfigItem(formData);
          createMessage.success('新增成功');
          closeModal();
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      const optionsColumns = ref([
        {
          title: '名称',
          dataIndex: 'name',
          width: 200,
          customRender: ({ record, index }) => {
            return h(Input, {
              value: record['name'],
              onChange: (e) => {
                record['name'] = e.target.value;
                dataRef.value['options'][index]['name'] = record['name'];
              },
            });
          },
        },
        {
          title: '值',
          dataIndex: 'value',
          width: 200,
          customRender: ({ record, index }) => {
            return h(Input, {
              value: record['value'],
              onChange: (e) => {
                record['value'] = e.target.value;
                dataRef.value['options'][index]['value'] = record['value'];
                setFieldsValue({ value: undefined });
              },
            });
          },
        },
        {
          title: '操作',
          dataIndex: 'value',
          width: 80,
          customRender: ({ index }) => {
            return h(DeleteOutlined, {
              style: 'color:red',
              onClick: () => {
                dataRef.value['options'].splice(index, 1);
              },
            });
          },
        },
      ]);
      const hanldeOptionsCreate = () => {
        if (isArray(dataRef.value['options'])) {
          dataRef.value['options'].push({
            name: '',
            value: '',
          });
        } else {
          dataRef.value['options'] = [];
          dataRef.value['options'].push({
            name: '',
            value: '',
          });
        }
      };

      return {
        registerModal,
        registerForm,
        getTitle,
        handleSubmit,
        isOrNooptions,
        dataRef,
        optionsColumns,
        hanldeOptionsCreate,
      };
    },
  });
</script>
